package kr.pe.asuraho;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.impl.cookie.BasicClientCookie;

public class StaticMethods {

	public static String capitalize(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return str;
		}
		return new StringBuilder(strLen).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString();
	}

	public static boolean isEmpty(Object data) {
		if (data == null) {
			return true;
		} else if ("".equals(nvl(data))) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isEmpty(Map<?, ?> data, String key) {
		if (data == null) {
			return true;
		} else if (data.isEmpty()) {
			return true;
		} else if (!data.containsKey(key)) {
			return true;
		} else if ("".equals(nvl(data.get(key)))) {
			return true;
		} else {
			return false;
		}
	}
	
	/***
	 * 로그파일 세팅
	 * @param fileName
	 */
	public static void setLog(String fileName){
		try {
			File log = new File("./log\\" + fileName + "-" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date(System.currentTimeMillis())) + ".txt");
			log.createNewFile();
			File errorLog = new File("./log\\Error-" + fileName + "-" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date(System.currentTimeMillis())) + ".txt");
			errorLog.createNewFile();

			System.setOut(new PrintStream(new FileOutputStream(log), true));
			System.setErr(new PrintStream(new FileOutputStream(errorLog), true));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/***
	 * 쿠키 생성
	 * @param name
	 * @param value
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static BasicClientCookie createCookie(String name, String value) throws UnsupportedEncodingException {
		return createCookie(name, value, ".mybogo.net", "/");
	}

	/***
	 * 쿠키 생성
	 * @param name
	 * @param value
	 * @param domain
	 * @param path
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static BasicClientCookie createCookie(String name, String value, String domain, String path) throws UnsupportedEncodingException {
		BasicClientCookie bc = new BasicClientCookie(name, new String(value.getBytes(), "UTF-8"));
		if (domain != null)
			bc.setDomain(domain);
		if (path != null)
			bc.setPath(path);
		bc.setExpiryDate(new Date(new Date().getTime() + (1000 * 60 * 60 * 24)));

		return bc;
	}
	
	/***
	 * Mybogo 로그인 정보 파싱
	 * @param html
	 * @return
	 */
	public static Map<String, String> parsingMybogoLoginInfo(String html){
		Map<String, String> result = new HashMap<String, String>();
		int start, end;
		
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_ID\" value=\"") + 45;
		end = html.indexOf("\">", start);
		result.put("MEMBER_ID", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_NAME\" value=\"") + 47;
		end = html.indexOf("\">", start);
		result.put("MEMBER_NAME", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_EMAIL\" value=\"") + 48;
		end = html.indexOf("\">", start);
		result.put("MEMBER_EMAIL", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_LEVEL\" value=\"") + 48;
		end = html.indexOf("\">", start);
		result.put("MEMBER_LEVEL", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_NO\" value=\"") + 45;
		end = html.indexOf("\">", start);
		result.put("MEMBER_NO", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_POINT\" value=\"") + 48;
		end = html.indexOf("\">", start);
		result.put("MEMBER_POINT", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_PASS\" value=\"") + 47;
		end = html.indexOf("\">", start);
		result.put("MEMBER_PASS", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_SEX\" value=\"") + 46;
		end = html.indexOf("\">", start);
		result.put("MEMBER_SEX", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"MEMBER_LOGIN_TIME\" value=\"") + 53;
		end = html.indexOf("\">", start);
		result.put("MEMBER_LOGIN_TIME", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"LOGOUT\" value=\"") + 42;
		end = html.indexOf("\">", start);
		result.put("LOGOUT", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"STR\" value=\"") + 39;
		end = html.indexOf("\">", start);
		result.put("STR", nvl(html.substring(start, end)));
		start = html.indexOf("<input type=\"hidden\" name=\"todo\" value=\"") + 40;
		end = html.indexOf("\">", start);
		result.put("todo", nvl(html.substring(start, end)));
		
		
		return result;
	}
	
	/***
	 * 쿠키정보 파싱
	 * @param html
	 * @return
	 */
	public static Map<String, String> parsingCookieInfo(String html){
		Map<String, String> result = new HashMap<String, String>();
		int start, end;
		
		start = html.indexOf("setCookie( 'MEMBER_ID', \"") +  25; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_ID", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_NAME', \"") +  27; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_NAME", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_EMAIL', \"") +  28; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_EMAIL", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_LEVEL', \"") +  28; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_LEVEL", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_NO', \"") +  25; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_NO", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_POINT', \"") +  28; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_POINT", nvl(html.substring(start, end)));
		
		start = html.indexOf("setCookie( 'MEMBER_SEX', \"") +  26; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_SEX", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'MEMBER_LOGIN_TIME', \"") +  33; 
		end = html.indexOf("\", 1 );", start);
		result.put("MEMBER_LOGIN_TIME", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'LOGOUT', \"") +  22; 
		end = html.indexOf("\", 1 );", start);
		result.put("LOGOUT", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'STR', \"") +  19; 
		end = html.indexOf("\", 1 );", start);
		result.put("STR", nvl(html.substring(start, end)));

		start = html.indexOf("setCookie( 'STR1', \"") +  20;
		end = html.indexOf("\", 1 );", start);
		result.put("STR1", nvl(html.substring(start, end)));
		
		return result;
	}
	
	/***
	 * 게시판 리스트 파싱
	 * @param html
	 * @return
	 */
	public static List<Map<String, String>> parsingBoardList(String html){
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		Map<String, String> data;
		String tr, url, title, date;
		int trStart, trEnd, urlStart, urlEnd, titleStart, titleEnd, dateStart, dateEnd;
		
		html = html.substring(html.indexOf("<table class=\"board01\" bgcolor=\"#ebebeb\">"));
		html = html.substring(html.indexOf("<tbody class=\"num\">") + 19);
		html = html.substring(0, html.indexOf("</tbody>"));	// TBODY 내용 이외의 것은 cut
		
		if(html.indexOf("등록된 글이 없습니다.") > 0) return result;
		
		while(html.indexOf("<tr>") != -1 ){
			trStart = html.indexOf("<tr>");
			html = html.substring(trStart);
			
			trEnd = html.indexOf("</tr>");
			
			tr = html.substring(0, trEnd+5);
			if(tr.indexOf("<script") == -1){	// TR중 광고 제거 : 즉 광고를 제거한 TR은 진짜다.
				
				urlStart = tr.indexOf("<a href=\""); // 9
				url = tr.substring(urlStart + 9);
				urlEnd = url.indexOf("\" class=\"Font9\"");
				url = nvl(url.substring(0, urlEnd));			// View URL 획득
				
				titleStart = tr.indexOf("class=\"Font9\">"); // 14
				title = tr.substring(titleStart + 14);
				titleEnd = title.indexOf("</a></td>");
				title = nvl(title.substring(0, titleEnd));			// Title 획득
				if(title.lastIndexOf("(") > 0){
					title  = title.substring(0, title.lastIndexOf("("));
				}
				
				dateStart = tr.indexOf("<td style=\"font-family:Verdana;font-size:11px;\">");
				date = tr.substring(dateStart + 48);
				dateStart = date.indexOf("<td style=\"font-family:Verdana;font-size:11px;\">"); // 48
				date = date.substring(dateStart + 48);
				dateEnd = date.indexOf("</td>");
				date = ("20" + nvl(date.substring(0, dateEnd))).replace("-", "");			// Date 획득
				
				
				data = new HashMap<String, String>();
				data.put("url", url);
				data.put("title", title);
				data.put("date", date);
				result.add(data);
				
			}
			
			html = html.substring(trEnd);
		}
		
		return result;
	}
	
	/***
	 * 게시판 상세화면 파싱
	 * @param html
	 * @return
	 */
	public static List<Map<String, String>> parsingBoardDetail(String html){
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		Map<String, String> data;
		String url, filename;
		int urlStart, urlEnd, filenameStart, filenameEnd;
		
		html = html.substring(html.indexOf("<img src='/images/icon/tor.jpg' align='absmiddle'>") + 50);
		html = html.substring(0, html.indexOf("</tr>"));	// download 링크들만 추출
		
		while(html.indexOf("<a href=\"./download.php") != -1 ){
			
			urlStart = html.indexOf("<a href=\"./download.php");
			html = html.substring(urlStart + 10);
			urlEnd = html.indexOf("\" class=\"link\"");
			url = nvl(html.substring(0, urlEnd));
			
			filenameStart = html.indexOf("class=\"link\"><span style=\"font-size:11px;\">");
			html = html.substring(filenameStart + 43);
			filenameEnd = html.indexOf("</span></a>");
			filename = nvl(html.substring(0, filenameEnd));
			
			if(indexOfList(url, ".torrent", ".smi")){
				data = new HashMap<String, String>();
				data.put("url", url);
				data.put("filename", filename);
				
				result.add(data);
			}
			html = html.substring(filenameEnd);
		}
		
		return result;
	}
	
	/***
	 * 인코딩된 URL정보를 디코딩해주는 메소드
	 * @param url
	 * @return
	 */
	public static String decodeURL(String hibogo_url, String url){
		
		url = url.replace("/download.php?down=", "");
		url = url.split("\\|\\|\\|")[0];
		
		StringBuilder sb = new StringBuilder();
		while(url.length() >= 3){
			sb.append((char)(Integer.parseInt(url.substring(0, 3), 16) - 91));
			url = url.substring(3);
		}
		
		String[] str = sb.toString().split("\\|\\|\\|");
		
		return "http://" + hibogo_url + "/cdsbData/" + str[1] + "/" + str[2] + "/" + str[0];
	}
	
	/***
	 * nvl 메소드
	 * @param obj
	 * @return
	 */
	public static String nvl(Object obj) {
		if (obj == null) return "";
		else if (obj instanceof String) {
			String str = (String) obj;
			if (str == null) return "";
			else return str.trim();
		} else {
			return obj.toString();
		}
	}
	
	/***
	 * 여러개 문자를 IndexOf하는 메소드
	 * @param text
	 * @param str
	 * @return
	 */
	public static boolean indexOfList(String text, String... str) {
		if (text == null || "".equals(text) || str == null || str.length == 0) return false;

		for (int i = 0; i < str.length; i++) {
			if (text.indexOf(str[i]) >= 0)
				return true;
		}

		return false;
	}
	
	/***
	 * 여러개 문자를 equals하는 메소드
	 * @param text
	 * @param str
	 * @return
	 */
	public static boolean equalsList(String text, String... str) {
		if (text == null || "".equals(text) || str == null || str.length == 0) return false;
		
		for (int i = 0; i < str.length; i++) {
			if (text.equals(str[i]))
				return true;
		}
		
		return false;
	}
	
	public static void cmdExec(String cmd){
		Process prc = null;
		BufferedReader br = null;
		String szLine = null;
		
		try {
			prc = Runtime.getRuntime().exec(cmd);
			br = new BufferedReader(new InputStreamReader(prc.getInputStream()));
			while ((szLine = br.readLine()) != null) {
				System.out.println(szLine);
			}
			br.close();
			prc.destroy();
		} catch (IOException e) {}
	}
	
	public static String crontabCode(String interval_code){
		String interval = null;
		if("m20".equals(interval_code)){
			interval = "0 */20 * * * ?";
		}else if("m30".equals(interval_code)){
			interval = "0 */30 * * * ?";
		}else if("h1".equals(interval_code)){
			interval = "0 0 * * * ?";
		}else if("h3".equals(interval_code)){
			interval = "0 0 */3 * * ?";
		}else if("h6".equals(interval_code)){
			interval = "0 0 */6 * * ?";
		}else if("h12".equals(interval_code)){
			interval = "0 0 */12 * * ?";
		}else if("d1".equals(interval_code)){
			interval = "0 0 0 * * ?";
		}else if("d2".equals(interval_code)){
			interval = "0 0 0 */2 * ?";
		}else if("d3".equals(interval_code)){
			interval = "0 0 0 */3 * ?";
		}
		
		return interval;
	}
}